package app

import (
	"fmt"
	validate "gin_template/core/validator"
	"gin_template/data/e"
	"net/http"
	"strings"

	"github.com/go-playground/validator/v10"

	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// BindAndValid 绑定参数并返回统一参数校验结果
func BindAndValid(c *gin.Context, form interface{}) (int, string) {
	err := c.ShouldBindBodyWith(form, binding.JSON)
	if err != nil {
		return http.StatusBadRequest, e.INVALID_PARAMS
	}
	valid := validation.Validation{}
	check, err := valid.Valid(form)
	if err != nil {
		return http.StatusInternalServerError, e.ERROR
	}
	if !check {
		MarkErrors(valid.Errors)
		return http.StatusBadRequest, e.INVALID_PARAMS
	}
	return http.StatusOK, e.SUCCESS
}

// BindAndValidWithError 绑定参数并返回具体参数校验结果
func BindAndValidWithError(c *gin.Context, form interface{}) (int, string, interface{}) {
	var validateErr interface{}
	err := c.ShouldBindBodyWith(form, binding.JSON)
	fmt.Println("=======111", err)
	if err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if ok {
			validateErr = removeTopStruct(errs.Translate(validate.Trans))
		}
		return http.StatusBadRequest, e.INVALID_PARAMS, validateErr
	}
	return http.StatusOK, e.SUCCESS, validateErr
}

func removeTopStruct(fields map[string]string) map[string]string {
	fmt.Println("removeTopStruct", fields)
	res := map[string]string{}
	for field, err := range fields {
		res[field[strings.Index(field, ".")+1:]] = err
	}
	return res
}
